import React from "react";
import { useForm } from "react-hook-form";
import request from "@/api/http_class";

import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import * as z from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useToast } from "@/hooks/use-toast";
import { DropzoneFileUploader } from "@/components/ui/file-uploader";
import { Button } from "@/components/ui/button";

const GotOcr: React.FC = () => {
  const [isSubmitting, setIsSubmitting] = React.useState<boolean>(false);
  const [result, setResult] = React.useState<string>();
  const [imageSrc, setImageSrc] = React.useState<string>();
  const { toast } = useToast();
  const formSchema = z.object({
    files: z.any().array(),
  });

  type FormValuesT = z.infer<typeof formSchema>;

  const defaultValues = {
    files: [],
  };
  const form = useForm<FormValuesT>({
    resolver: zodResolver(formSchema),
    defaultValues: defaultValues,
  });

  const handleFileChange = (value: any) => {
    console.log(value);
    if (value instanceof Array) {
      const reader = new FileReader();
      reader.onloadend = () => {
        setImageSrc(reader.result as string);
      };
      reader.readAsDataURL(value[0]);
    }
  };

  const handleFormSubmit = (values: any) => {
    console.log(values);
    if (values.files.length) {
      const formData = new FormData();
      // 将全部数据转换为FormData格式
      values.files.forEach((item: File) => {
        console.log(item);
        formData.append("files", item);
      });
      console.log(formData);
      request({
        url: `/ocr/image/`,
        method: "POST",
        data: formData,
        headers: { "Content-Type": "multipart/form-data" },
      }).then(
        (res: any) => {
          console.log(res);
          setResult(res.data);
          toast({
            variant: "success",
            title: "数据导入成功",
            description: "",
          });
        },
        (err: any) => {
          console.log(err);
          toast({
            variant: "destructive",
            title: "数据导入失败",
            description: "请检查网络或联系系统管理员",
          });
        }
      );
    } else {
      console.log("no files");
    }
  };

  return (
    <div className="p-6 text-center">
      <span className="text-3xl font-bold">OCR识别演示</span>
      <Form {...form}>
        <form
          onSubmit={form.handleSubmit(handleFormSubmit)}
          className="w-full space-y-8 flex flex-col justify-center"
        >
          <div className="flex flex-col gap-4">
            <FormField
              control={form.control}
              name="files"
              render={({ field }) => (
                <FormItem>
                  <FormControl>
                    <DropzoneFileUploader
                      value={field.value}
                      onChange={(file) => {
                        handleFileChange(file);
                        field.onChange(file);
                      }}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </div>
          <Button disabled={isSubmitting} className="ml-auto" type="submit">
            提交
          </Button>
        </form>
      </Form>
      <div className="flex p-6">
        <div className="w-1/2">
          <img src={imageSrc} alt="Picture" />
        </div>
        <div className="w-1/2">{result}</div>
      </div>
    </div>
  );
};

export default GotOcr;
